package com.onlineMIS.action.headQ.barCodeGentor;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.onlineMIS.ORM.DAO.JspLoadResult;
import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Brand;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.BrandPriceIncrease;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Color;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductBarcode;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductBarcodeVO;
import com.onlineMIS.ORM.entity.headQ.inventory.JinSuanOrderTemplate;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.StrCheckUtils;
import com.onlineMIS.common.loggerLocal;
import com.opensymphony.xwork2.ActionContext;

@Controller
public class ProductJSPAction extends ProductAction {

	private static final long serialVersionUID = -161455229996547363L;

	//
	private final String templateFileName = "BarcodeTemplate.xls";
	private InputStream excelStream;
	private String excelFileName = "barcodeFiles.xls";
	private final String barcodeCreation = "BarcodeCreationTemplate.xls";
	private final String tagPrintName = "TagPrintTemplate.xls";

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public String getExcelFileName() {
		return excelFileName;
	}

	public void setExcelFileName(String excelFileName) {
		this.excelFileName = excelFileName;
	}

	public String getTemplateFileName() {
		return templateFileName;
	}

	/**
	 * 导出产品信息 ->选中导出
	 */
	public String execute() throws Exception {
		loggerLocal.info("ProductJSPAction - execute");
		
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Map<String, Object> map = productService.generateExcelReport(formBean.getBarcodes(),request.getRealPath("/") + "WEB-INF\\template\\" + templateFileName);
		excelStream = (InputStream) map.get("stream");
		return "report";
	}
	
	/**
	 * 导出产品信息 ->条件导出
	 */
	public String exportByCondition() throws Exception {
		loggerLocal.info("ProductJSPAction - exportByCondition");
		
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Map<String, Object> map = productService.generateExcelReportByCondition(formBean.getProductBarcode(), formBean.getBrandIds(),formBean.getBelongTo2(),formBean.getStartDate(), formBean.getEndDate(), formBean.getNeedCreateDate(),this.getPage(), this.getRows(), this.getSort(), this.getOrder(),request.getRealPath("/") + "WEB-INF\\template\\" + templateFileName);
		excelStream = (InputStream) map.get("stream");
		return "report";
	}

	
	/**
	 * 导出条码打印->选中打印
	 * @return
	 * @throws Exception
	 */
	public String exportToPrintBarcode() throws Exception {
		loggerLocal.info("ProductJSPAction - exportToPrintBarcode");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Map<String, Object> map = productService.generateJinsuanExcelReport(formBean.getBarcodes(),contextPath + "WEB-INF\\template\\" + JinSuanOrderTemplate.JinsuanFileName);
		excelStream = (InputStream) map.get("stream");
		return "report";
	}
	
	/**
	 * 导出条码打印->条件打印
	 * @return
	 * @throws Exception
	 */
	public String exportToPrintBarcodeAll() throws Exception {
		loggerLocal.info("ProductJSPAction - exportToPrintBarcode");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Map<String, Object> map = productService.exportToPrintBarcodeAll(formBean.getProductBarcode(), formBean.getBrandIds(),formBean.getBelongTo2(),formBean.getStartDate(), formBean.getEndDate(), formBean.getNeedCreateDate(),this.getPage(), this.getRows(), this.getSort(), this.getOrder(),contextPath + "WEB-INF\\template\\" + JinSuanOrderTemplate.JinsuanFileName);
		excelStream = (InputStream) map.get("stream");
		return "report";
	}

	/**
	 * 导出条码给其他系统再生成 ->选中导出
	 */
	public String exportBarcodeForCreation() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Map<String, Object> map = productService.generateBarcodeFile(formBean.getBarcodes(),contextPath + "WEB-INF\\template\\" + barcodeCreation);
		excelStream = (InputStream) map.get("stream");
		return "report";
	}
	
	/**
	 * 导出条码给其他系统再生成 ->条件导出
	 */
	public String exportBarcodeForCreationAll() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Map<String, Object> map = productService.generateBarcodeFileAll(formBean.getProductBarcode(), formBean.getBrandIds(),formBean.getBelongTo2(),formBean.getStartDate(), formBean.getEndDate(), formBean.getNeedCreateDate(),this.getPage(), this.getRows(), this.getSort(), this.getOrder(),contextPath + "WEB-INF\\template\\" + barcodeCreation);
		excelStream = (InputStream) map.get("stream");
		return "report";
	}
		

	/**
	 * 吊牌打印 ->选中打印
	 */
	public String tagPrint() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Map<String, Object> map = productService.generateTagPrintFile(formBean.getBarcodes(),contextPath + "WEB-INF\\template\\" + tagPrintName);
		excelStream = (InputStream) map.get("stream");
		return "report";
	}
	
	/**
	 * 吊牌打印 ->条件打印
	 */
	public String tagPrintAll() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");

		Map<String, Object> map = productService.generateTagPrintFileAll(formBean.getProductBarcode(), formBean.getBrandIds(),formBean.getBelongTo2(),formBean.getStartDate(), formBean.getEndDate(), formBean.getNeedCreateDate(),this.getPage(), this.getRows(), this.getSort(), this.getOrder(),contextPath + "WEB-INF\\template\\" + tagPrintName);
		excelStream = (InputStream) map.get("stream");
		return "report";
	}
	
	/**
	 * when user scan the product by product code
	 * 
	 * @return
	 */
	public String scanByProductCode() {
		loggerLocal.info("ProductJSPAction - scanByProductCode");
		
		String productCode = Common_util.decode(formBean.getProductBarcode().getProduct().getProductCode());
		List<ProductBarcode> products = productService.getProductsForSimiliarProductCode(productCode,null, 0,
				formBean.getStoreId(), formBean.getPager());
		uiBean.setProducts(products);
		uiBean.setIndex(formBean.getIndexPage());

		return "ProductCodeSearchProducts";
	}

	/**
	 * when user scan the product by product code
	 * 
	 * 这个只为总部使用的action, 会计输入货品的时候查找库存
	 * 
	 * @return
	 * @throws Exception
	 */
	public String scanByProductCodeHeadq() throws Exception {
		loggerLocal.info("ProductJSPAction - scanByProductCodeHeadq");
		String productCode = "";
		String factoryCode = "";
		if (StringUtils.isNotBlank(formBean.getProductBarcode().getProduct().getProductCode())) {
			productCode = Common_util.decode(formBean.getProductBarcode().getProduct().getProductCode());
		}
		if (StringUtils.isNotBlank(formBean.getProductBarcode().getProduct().getFactoryCode())) {
			factoryCode = Common_util.decode(formBean.getProductBarcode().getProduct().getFactoryCode());
		}
				
		List<ProductBarcodeVO> products = productService.getProductsForSimiliarProductCodeHeadq(productCode,factoryCode, 0,formBean.getStoreId(), formBean.getPager());
		uiBean.setProductVOs(products);
		uiBean.setIndex(formBean.getIndexPage());

		return "ProductCodeSearchProductsHeadq";
	}

	/**
	 * pre-create barcode product
	 */
	public String preCreateProduct() {
		loggerLocal.info("ProductJSPAction - preCreateProduct");

		uiBean.setBasicData(productService.prepareBarcodeSourceDataForHead());

		productService.prepareCreateProductUIForm(formBean);

		return "create";
	}

	/**
	 * view the product infromation
	 * 
	 * @return
	 */
	public String viewProduct() {
		loggerLocal.info("ProductJSPAction - searchForUpdate");

		productService.prepareBarcodeSourceData();

		ProductBarcode product = productService.getProductsByBarcode(formBean.getProductBarcode().getBarcode());
		if (product == null) {
			System.out.print("无法找到相应信息");
		}

		uiBean.setProduct(product);

		uiBean.setCanViewRecCost(true);

		return "ViewProduct";
	}

	/**
	 * 客户查找图片
	 * 
	 * @return
	 */
	public String preSearchTwo() {
		loggerLocal.info("ProductJSPAction - preSearchTwo");

		uiBean.setBasicData(productService.prepareBarcodeSourceData());
		List<HeadqBrand> headqBrands = new ArrayList<HeadqBrand>();
		HeadqBrand headqBrandQX = new HeadqBrand();
		headqBrandQX.setId(Brand.BELONG_TO_QX);
		headqBrandQX.setName(Brand.belongToMap.get(Brand.BELONG_TO_QX));
		HeadqBrand headqBrandXLC = new HeadqBrand();
		headqBrandXLC.setId(Brand.BELONG_TO_XLC);
		headqBrandXLC.setName(Brand.belongToMap.get(Brand.BELONG_TO_XLC));
		headqBrands.add(headqBrandQX);
		headqBrands.add(headqBrandXLC);
		uiBean.setHeadqBrands(headqBrands);

		return "searchTwo";
	}

	/**
	 * search the product information for update
	 * 
	 * @return
	 */
	public String searchForUpdate() {
		loggerLocal.info("ProductJSPAction - searchForUpdate");
		uiBean.setBasicData(productService.prepareBarcodeSourceDataForHead());

		ProductBarcode product = productService.getProductsByBarcode(formBean.getProductBarcode().getBarcode());
		if (product == null) {
			addActionMessage("不能找到对应产品");
		} else {
			
			List<Color> colors = productService.getExcludeColors(product.getProduct().getProductId(),product.getColor());
			uiBean.getBasicData().setColorList(colors);
			uiBean.setProduct(product);
			formBean.setProductBarcode(product);
		}

		return SUCCESS;
	}

	/**
	 * when user press the search hyperlink
	 * 
	 * @return
	 */
	public String preSearch() {
		loggerLocal.info("ProductJSPAction - preSearch");

		uiBean.setBasicData(productService.prepareBarcodeSourceData());

		return "search";
	}

	/**
	 * update the product information
	 * 
	 * @return
	 */
	public String update() {
		loggerLocal.info("ProductJSPAction - update");
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		Response response = productService.updateProduct(formBean.getInventory(),formBean.getInventoryFileName(),formBean.getProductBarcode(),loginUserInfor);
		if (response.isSuccess())
			return "update";
		else {
			addActionError(response.getMessage());
			return searchForUpdate();
		}
	}

	/**
	 * delete the product information
	 * 
	 * @return
	 */
	public String delete() {
		loggerLocal.info("ProductJSPAction - delete");

		productService.deleteProductBarcode(formBean.getProductBarcode().getId());
		return "delete";
	}

	/**
	 * scan the brands by brand name
	 * 
	 * @return
	 */
	public String scanBrand() {
		loggerLocal.info("ProductJSPAction - scanBrand");

		String brandName = Common_util.decode(formBean.getProductBarcode().getProduct().getBrand().getBrand_Name());

		List<Brand> brands = productService.searchBrands(brandName);

		uiBean.setBrands(brands);

		return "BrandList";
	}

	public String searchColor() {
		loggerLocal.info("ProductJSPAction - scanColor");

		String colorNames = Common_util.decode(formBean.getColorNames());

		List<Color> colors = productService.searchColors(colorNames);

		uiBean.setColors(colors);

		return "ColorList";
	}

	/**
	 * 进入文件管理页面
	 * 
	 * @return
	 */
	public String preSystemFildEdit() {
		loggerLocal.info("ProductJSPAction - preSystemFildEdit");

		return "preSystemFildEdit";
	}

	/**
	 * 批量删除条码
	 * 
	 * @return
	 */
	public String batchDeleteBarcode() {
		loggerLocal.info("ProductJSPAction - batchDeleteBarcode");
		productService.prepareBatchInsertBarcodeUI(formBean, uiBean);
		Response response = new Response();
		String isReloadRandom = (String) ActionContext.getContext().getSession().get(JspLoadResult.IS_RELOAD);
		if (StringUtils.isBlank(isReloadRandom) || !isReloadRandom.equals(formBean.getRandom()) ) {
			response = productService.batchDeleteBarcode(formBean.getInventory());
	
			if (response.isSuccess()) {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
			}
			ActionContext.getContext().getSession().put(JspLoadResult.IS_RELOAD, formBean.getRandom());//通过前台的随机数来确认，是否是重新加载框架
		}
		return "batchInsertBarcode";
	}

	/**
	 * 批量修改条码
	 * 
	 * @return
	 */
	public String batchUpdateBarcode() {
		loggerLocal.info("ProductJSPAction - batchUpdateBarcode");
		productService.prepareBatchInsertBarcodeUI(formBean, uiBean);
		Response response = new Response();
		String isReloadRandom = (String) ActionContext.getContext().getSession().get(JspLoadResult.IS_RELOAD);
		if (StringUtils.isBlank(isReloadRandom) || !isReloadRandom.equals(formBean.getRandom()) ) {
			response = productService.batchUpdateBarcode(formBean.getInventory());
			if (response.isSuccess()) {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
				
			}else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
			}
			ActionContext.getContext().getSession().put(JspLoadResult.IS_RELOAD, formBean.getRandom());//通过前台的随机数来确认，是否是重新加载框架
		}		
		return "batchInsertBarcode";
	}

	/**
	 * 进入 brand price 提价的页面
	 * 
	 * @return
	 */
	public String preBrandPriceIncrease() {
		loggerLocal.info("ProductJSPAction - preBrandPriceIncrease");

		return "brandPriceIncrease";
	}

	public String preEditBrandPriceIncrease() {
		loggerLocal.info("ProductJSPAction - preEditBrandPriceIncrease");

		BrandPriceIncrease bpIncrease = formBean.getBpi();
		int yearId = bpIncrease.getYear().getYear_ID();
		int quarterId = bpIncrease.getQuarter().getQuarter_ID();
		int brandId = bpIncrease.getBrand().getBrand_ID();

		Response response = brandPriceIncreaseService.getBPI(yearId, quarterId, brandId);

		if (response.isSuccess()) {
			bpIncrease = (BrandPriceIncrease) response.getReturnValue();
		} else
			addActionError(response.getMessage());

		brandPriceIncreaseService.prepareEditBrandPriceIncreaseUI(formBean, uiBean);

		return "editBrandPriceIncrease";
	}

	/**
	 * 进入批量插入条码页面
	 * 
	 * @return
	 */
	public String preBatchInsertBarcode() {
		loggerLocal.info("ProductJSPAction - preBatchInsertBarcode");

		productService.prepareBatchInsertBarcodeUI(formBean, uiBean);

		return "batchInsertBarcode";
	}

	/**
	 * 批量插入页面
	 * 
	 * @return
	 */
	public String batchInsertBarcode() {
		loggerLocal.info("ProductJSPAction - batchInsertBarcode");
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		productService.prepareBatchInsertBarcodeUI(formBean, uiBean);
		Response response = new Response();
		String isReloadRandom = (String) ActionContext.getContext().getSession().get(JspLoadResult.IS_RELOAD);
		if (StringUtils.isBlank(isReloadRandom) || !isReloadRandom.equals(formBean.getRandom()) ) {
			try {
				response = productService.batchInsertBarcode(formBean.getInventory(),formBean.getProductBarcode().getProduct(),loginUserInfor);
			} catch (Exception e) {
				e.printStackTrace();
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_ABNORMAL, response.getMessage()));
			}

			if (response.isSuccess()) {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_SUCCESS, response.getMessage()));
			}else {
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
			}
			ActionContext.getContext().getSession().put(JspLoadResult.IS_RELOAD, formBean.getRandom());//通过前台的随机数来确认，是否是重新加载框架
		}
		return "batchInsertBarcode";
	}

	/**
	 * 文件上传
	 * 
	 * @return
	 */
	public String uploadFile() {
		loggerLocal.info("ProductJSPAction - batchInsertBarcode");
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		Response response = new Response();

		try {
			response = productService.uplodFile(formBean.getInventory(), formBean.getInventoryFileName(),formBean.getComment(),loginUserInfor);
			addActionMessage(response.getMessage());
		} catch (Exception e) {
			response.setFail("保存条码出现错误  : " + e.getMessage());

		}
		return "preSystemFildEdit";
		
	}
	
	/**
	 * 文件下载
	 * @return
	 * @throws Exception
	 */
	public String downloadFile() throws Exception {
		loggerLocal.info("ProductJSPAction - downloadFile ");
		String fileName = formBean.getFileName();
		if (StrCheckUtils.isChinese(fileName.substring(0,fileName.indexOf(".")))) {
			
			String suffix = fileName.substring(fileName.indexOf(".")+1,fileName.length());
			
			excelFileName = Common_util.getUUID() + "."+suffix;
		}else {
			excelFileName = formBean.getFileName();
		}
		excelStream = productService.downloadFile(formBean.getFileName());
		
		return "report";
	}	

}
